<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="20" :xs="24">
        <el-form
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="queryParams.roleName"
              placeholder="请输入角色名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="权限字符" prop="roleKey">
            <el-input
              v-model="queryParams.roleKey"
              placeholder="请输入权限字符"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="角色状态"
              clearable
              size="small"
              style="width: 140px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
            >重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <!--角色数据-->
      <el-col>
        <el-table
          v-loading="listLoading"
          :data="roleList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="角色编号" align="center" prop="roleId" />
          <el-table-column
            label="角色名称"
            align="center"
            prop="roleName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="权限字符"
            align="center"
            prop="roleKey"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="显示顺序" align="center" prop="roleSort" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="创建日期" align="center" width="200">
            <template slot-scope="scope">
              <i class="el-icon-time" />
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="220"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.size"
          style="float: right"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改角色信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="form.roleName" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="权限字符" prop="roleKey">
              <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="角色顺序" prop="roleSort">
              <el-input-number
                v-model="form.roleSort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="菜单权限">
              <el-tree
                ref="menu"
                v-loading="listLoading"
                :data="menuOptions"
                show-checkbox
                node-key="id"
                empty-text="加载中，请稍后"
                :props="defaultProps"
              /> </el-form-item></el-col>
          <el-col>
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listRole,
  addRole,
  getRole,
  updateRole,
  deleteRole
} from '@/api/system/role'
import { getMenuTreeSelect, getRoleMenuTreeSelect } from '@/api/system/menu'
export default {
  data() {
    return {
      roleList: null,
      listLoading: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        rolerName: undefined,
        roleKey: undefined,
        status: undefined
      },
      statusOptions: [
        { dictLabel: '正常', dictValue: '0' },
        { dictLabel: '停用', dictValue: '1' }
      ],
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: 'blur'
          }
        ],
        roleKey: [
          { required: true, message: '权限字符不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度不能超过 100 个字符',
            trigger: 'blur'
          }
        ],
        roleSort: [
          { required: true, message: '角色顺序不能为空', trigger: 'blur' }
        ]
      },
      form: {},
      single: true,
      multiple: true,
      title: '',
      open: false,
      menuOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listRole(this.queryParams).then((response) => {
        // console.log(response);
        this.total = response.total
        this.roleList = response.rows
        this.listLoading = false
      })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增角色按钮
    handleAdd() {
      getMenuTreeSelect().then((res) => {
        this.reset()
        this.open = true
        this.menuOptions = res.data
        // 状态默认停用
        this.form.status = '1'
        this.form.roleSort = 0
        this.title = '新增角色'
      })
    },
    // 更新角色,回显数据
    handleUpdate(row) {
      this.reset()
      const roleId = row.roleId || this.ids
      getRole(roleId).then((res) => {
        this.form = res.data
        this.open = true
      })
      getRoleMenuTreeSelect(roleId).then((res) => {
        this.listLoading = true
        this.menuOptions = res.menus
        this.$refs.menu.setCheckedKeys(res.checkedKeys)
        this.listLoading = false
        // console.log(res.checkedKeys);
      })
    },
    // 删除角色
    handleDelete(row) {
      const roleIds = row.roleId || this.ids
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRole(roleIds).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 角色状态修改
    handleStatusChange(row) {
      const status = row.status === '1' ? '已停用' : '已启用'
      updateRole(row).then((res) => {
        this.$message({
          type: status === '已启用' ? 'success' : 'warning',
          message: row.roleName + status
        })
        this.reset()
      })
    },
    reset() {
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleKey: undefined,
        roleSort: undefined,
        status: 0,
        remark: undefined,
        menuIds: []
      }
      this.resetForm('form')
    },
    cancel() {
      this.open = false
      this.reset()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (!valid) return
        if (this.title === '新增角色') {
          this.form.menuIds = this.$refs.menu.getCheckedKeys()
          addRole(this.form).then((res) => {
            this.$message({
              type: 'success',
              message: '恭喜您,' + this.form.roleName + '新增成功!'
            })
            this.getList()
            this.open = false
            this.reset()
          })
        } else {
          this.form.menuIds = this.$refs.menu.getCheckedKeys()
          updateRole(this.form).then((res) => {
            this.$message({
              type: 'success',
              message: '恭喜您,' + this.form.roleName + '修改成功!'
            })
            this.getList()
            this.open = false
            this.reset()
          })
        }
      })
    }
  }
}
</script>

